package com.lucky.common.controller;

import com.lucky.common.base.BaseController;
import com.lucky.common.cache.ParamCache;
import com.lucky.common.cache.RightCache;
import com.lucky.common.config.security.AppUserDetailsService;
import com.lucky.common.enums.AppConst;
import com.lucky.common.pojo.dto.LoginDTO;
import com.lucky.common.pojo.po.UserPO;
import com.lucky.common.pojo.vo.PermVO;
import com.lucky.common.service.*;
import com.lucky.common.util.TreeUtil;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.Resource;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.context.HttpSessionSecurityContextRepository;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.Assert;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import java.util.*;

@Controller
@RequestMapping("/login")
public class LoginController extends BaseController {

	private static final Logger log = LoggerFactory.getLogger(LoginController.class);
	
	@Resource
	UserService userService;
	@Resource
	AppUserDetailsService userDetailsService;
	@Resource
	OrgService orgService;
	@Resource
	ParamService paramService;
	@Resource
	LoginService loginService;
	@Resource
	PermService PermService;
	@Resource
	PasswordEncoder  passwordEncoder;

	@Resource
	private RightCache rightCache;

	private ModelAndView error(ModelMap model, String errorMsg) {
		model.put("errMsg", errorMsg);
		return new ModelAndView("index");
	}
	private ModelAndView errorLogin(ModelMap model) {
        model.putIfAbsent("errMsg", "用户名或密码错误");
		if("0".equals(paramService.getCacheValue(ParamCache.ENV))) {
			return redirectView("/error/notLogin");
		}else {
			return new ModelAndView("index");
		}

	}


	@PostMapping("/login")
	public ModelAndView login(@Valid LoginDTO loginDto, ModelMap model, BindingResult br, HttpSession session) {

		String username  = loginDto.getUsername();
		String password = loginDto.getPassword();

		String sessionVcode = (String) session.getAttribute("vcode");
		String vcode = loginDto.getVcode();

		Assert.hasText(username, "请输入用户名");
		Assert.hasText(password, "请输入密码");
		Assert.hasText(vcode, "请输入验证码");
		Assert.isTrue(vcode.equals(sessionVcode), "验证码错误");


		userDetailsService.login(session, username, password);

		// 认证成功后
		return redirectView("main");
	}

	@RequestMapping("/main")
	private String dash(HttpSession session) {
		return  "main";
	}

	//用户无权限跳转
	@RequestMapping("/unauthorized")
	public String unauthorized(ModelMap model) {
		return  "error/unauthorized";
	}
	
	//用户登录后主页
	@RequestMapping("/dashboard")
	public String dashboard(HttpSession session, ModelMap model) {
		Set<String> roleSet = (Set<String>) session.getAttribute("role");
		return  "dashboard";
	}
	
	//用户登录后主页
	@RequestMapping("/header")
	public String header(HttpSession session, ModelMap model) {
		return  "include/header";
	} 
	
	//用户登录后主页
	@RequestMapping("/nav")
	public String nav(HttpSession session, ModelMap model) {
		UserPO user = (UserPO) session.getAttribute(AppConst.userPO);
		List<String> roles = userService.queryRoles(user.getUsername());
		List<PermVO> lp = new LinkedList<>();
		roles.forEach(r->lp.addAll(rightCache.roleRightMap.get(r)));
		List<PermVO> tree = TreeUtil.makeTree(lp, p->Objects.equals(p.getSupRightCodeId(), 0L), (p, c)-> Objects.equals(p.getId(), c.getSupRightCodeId()), PermVO::setChildList);

		model.addAttribute("navTreeList",tree.get(2));
		return  "include/nav";
	}
	
	@RequestMapping("/logout")
	public String logout(HttpSession session, ModelMap model) {
		while(session.getAttributeNames().hasMoreElements()){
			session.removeAttribute(session.getAttributeNames().nextElement());
		}
		return  "index";
	}
	
	
	//密码处理
	private String getPwd(String pwd) {
		StringBuilder sb1 = new StringBuilder();
		StringBuilder sb2 = new StringBuilder();
		
		int length = pwd.length();
		for(int i=0; i<length; i++) {
			sb1.append((pwd.charAt(i)-100));
		}
		pwd = sb1.toString();
		
		length = pwd.length()/2;
		for(int i=0; i<length; i++) {
			char t = (char) (Integer.parseInt(pwd.substring(i*2, i*2+2))+7);
			sb2.append(t);
		}
		return sb2.toString();
	}

}
